package brinaryTree;

import java.util.HashMap;
import java.util.Map;

public class N106_BuildTreeFromInorderAndPostorderTraversal {
    private int post_index;
    private int[] postorder;
    private int[] inorder;
    private Map<Integer, Integer> val_idx_map = new HashMap<>();

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        this.inorder = inorder;
        this.postorder = postorder;
        this.post_index = postorder.length - 1;
        for (int i = 0; i < inorder.length; i++)
            this.val_idx_map.put(inorder[i], i);
        return build(0, inorder.length - 1);

    }

    public TreeNode build(int in_left, int in_right) {
        if (in_left > in_right) return null;

        int node_val = this.postorder[post_index];
        TreeNode node = new TreeNode(node_val);

        int index = val_idx_map.get(node_val);

        this.post_index--;

        node.right = build(index + 1, in_right);
        node.left = build(in_left, index - 1);

        return node;
    }

}
